import { createStore } from 'vuex'

import { getUserInfo } from '~/api/user/index';
import { postUserLogin } from '~/api/user/login_register';
import { setToken,removeToken } from '~/composables/auth'

// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            // 用户信息
            user: {},
            asideWidth: "250px",
            menus: [
                {
                    name: "菜单管理",
                    path: "/menu",
                    icon: "el-icon-s-home",
                    child: [
                        {
                            name: "菜单列表",
                            path: "/menu/list",
                            frontpath: "/menu/list",
                        }
                    ]
                },
            ]
        }
    },
    mutations: {
        handleAsideWidth(state) {
            state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
        },

        // 菜单
        SET_MENUS(state, menus) {
            state.menus = menus
        },

        // 记录用户信息
        SET_USERINFO(state, user) {
            state.user = user
        },
    },
    actions: {
        //获取菜单
        GetMenuList({ commit }, menuList) {
            commit('SET_MENUS', menuList)
        },

        //登录
        postUserLogin({ commit }, { username, password }) {
            // 存储token

            return new Promise((resolve, reject) => {
                postUserLogin(username, password).then(res => {
                    setToken(res.data.token)
                    resolve(res.data)
                }).catch(err => reject(err))
            })
        },

        // 获取当前登录用户信息
        getUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    commit("SET_USERINFO", res.data)
                    commit("SET_MENUS", res.data.menus)
                    // commit("SET_ROLESNAMES", res.data.roles)
                    // commit("SET_PERMISSIONS", res.data.menu_permission.map(o => o[0] + ',' + o[1]))
                    resolve(res.data)
                }).catch(err => reject(err))
            })

        },

        // 退出登录
        logout({ commit }) {
            // 清除cookie里的token
            removeToken()
            // 清除当前用户状态
            commit("SET_USERINFO", {})

            // // 删除cookie
            // deleteCookie("admin-token");
            // deleteCookie("tabList");
        }

    }
})

export default store